package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.Strategy;
import cn.com.dashihui.web.service.WxStrategyService;

public class WxStrategyController extends BaseController{
	private WxStrategyService service=new WxStrategyService();

	public void index(){
		 render("index.jsp");
	}
	public void list(){
		renderSuccess(service.findAllWithCount());
	}
	public void toAdd(){
		render("add.jsp");
	}

	/**
	 * 添加
	 * @return -1：异常，0：成功，1：标题为空，2：标题过长，3：概要为空，4：概要过长，5：内容为空，6：图片上传失败
	 */
	public void doAdd(){
		//缩略图
		UploadFile thumb = getFile("thumb");
		//分类
		int type = getParaToInt("category",0);
		//标题
		String title = getPara("name");
		//显示
		int isShow = getParaToInt("isShow",0);
		//排序
		int orderNo = getParaToInt("orderNo",0);
		if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>100){
			renderResult(2);
			return;
		}else{
			//保存
			Strategy article = new Strategy()
				.set("title", title)
				.set("type", type)
				.set("isShow", isShow)
				.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
				.set("orderNo", orderNo);
			//如果上传了图片，则上传至FTP，并记录图片文件名
			if(thumb!=null){
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.WX_ARTICLE_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(4);
					return;
				}
				article.set("thumb", dir.concat(thumbFileName));
			}
			if(service.addStrategy(article)){
				renderSuccess(service.findById(article.getInt("id")));
				return;
			}
		}
		renderFailed();
	}
	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("edit.jsp");
	}
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：标题为空，2：标题过长，3：概要为空，4：概要过长，5：内容为空，6：图片上传失败
	 */
	public void doEdit(){
		//缩略图
		UploadFile thumb = getFile("thumb");
		//ID
		String strategyid = getPara("strategyid");
		//分类
		int type = getParaToInt("category",0);
		//标题
		String title = getPara("name");
		//显示
		int isShow = getParaToInt("isShow",0);
		//旧图片
		String thumbOld = getPara("thumbOld");
		if(StrKit.isBlank(title)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>100){
			renderResult(2);
			return;
		}else{
			//更新
			Strategy article = new Strategy()
				.set("id", strategyid)
				.set("title", title)
				.set("type", type)
				.set("isShow", isShow)
				.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
			if(thumb!=null){
				//如果修改了图片，则上传新图片，删除旧图片
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.WX_ARTICLE_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(4);
					return;
				}
				article.set("thumb", dir.concat(thumbFileName));
				if(service.editStrategy(article)){
					try {
						deleteFromFtp(thumbOld);
					} catch (IOException e) {
						logger.error("更新时，旧图片"+thumbOld+"删除失败！");
						e.printStackTrace();
					}
					renderSuccess(service.findById(Integer.valueOf(strategyid)));
					return;
				}
			}else if(service.editStrategy(article)){
				renderSuccess(service.findById(Integer.valueOf(strategyid)));
				return;
			}
		}
		renderFailed();
	}
	
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功
	 */
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0){
			Strategy article = service.findById(id);
			//先判断如果上传了图片，则删除图片
			if(!StrKit.isBlank(article.getStr("thumb"))){
				try {
					deleteFromFtp(article.getStr("thumb"));
				} catch (IOException e) {
					logger.error("删除时，相关图片"+article.getStr("thumb")+"删除失败！");
					e.printStackTrace();
				}
			}
			//然后再对记录进行删除
			article.delete();
			renderSuccess();
			return;
		}
		renderFailed();
	}
	
	/**
	 * 分类排序
	 * wing
	 * 2015-10-26
	 */
	 public void doSort(){
    	Map<String,String[]> params = getParaMap();
    	if(params!=null&&params.size()!=0&&params.containsKey("sortKey")){
    		String sortKey = params.get("sortKey")[0];
    		Map<String,String> sortMap = new HashMap<String,String>();
    		for(String key : params.keySet()){
    			if(!key.equals("sortKey")){
    				String id = key.replace(sortKey, "");
    				String no = params.get(key)[0];
    				if(StrKit.isBlank(no)||no.length()>3){
    					no = "0";
    				}
    				sortMap.put(id, no);
    			}
    		}
    		service.sortCategory(sortMap);
    		renderSuccess();
    		return;
    	}
    	renderFailed();
    }
}
